package com.hongshan.wallet.core.trading

import android.app.Application
import android.databinding.ObservableField
import android.view.View
import com.hongshan.wallet.BuildConfig
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.base.SingleLiveEvent
import com.hongshan.wallet.bean.OrderDescBean
import com.hongshan.wallet.copyStr
import com.hongshan.wallet.format
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.EncryptUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.trading
 * @author   : zhangxx
 * @date     : 2019/3/28
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
class OrderDescViewModel(application: Application) : MyViewModel(application) {

    val overdueTime = ObservableField("")
    val overdueStatus =ObservableField("剩余收款时间")

    val money = ObservableField("10000.00")
    val orderCode = ObservableField("")
    //    val releaseTime = ObservableField("10000.00")
    val receiveTime = ObservableField("")
    //    val completeTime = ObservableField(" .00")
    val collectionType = ObservableField("")
    val collectionAcc = ObservableField("")
    val remark = ObservableField("")
    val receiveReady = ObservableField(false)
    val tradingStatus = ObservableField("")
    val commissionMoney = ObservableField("")
    val check_code = ObservableField("")
    val wxShowName = ObservableField(false)
    val wxName = ObservableField("")

    val showReceiveConfrimDialog = SingleLiveEvent<OrderDescBean>()
    val confirmEnable = SingleLiveEvent<Boolean>()

    var desc: OrderDescBean? = null
    var job: Job? = null

    val receiveConfirm = View.OnClickListener {
        desc?.run { showReceiveConfrimDialog.value = desc }
    }

    val copyOrderCode = View.OnClickListener {
        copyStr(orderCode.get())
    }

    fun receiveConfirm() {
        desc?.run {
            val userIdsStr = MyApplication.user?.account_id.toString()
            val moneyStr = total_fee?:""
            val markStr = goods
            val dtStr = (System.currentTimeMillis() / 1000).toString()
            showLoading.call()
            confirmEnable.value = false
            GlobalScope.launch(Dispatchers.Main) {
                val deferred = GlobalScope.async(Dispatchers.IO) {
                    tryRun {
                        HttpClient.httpApi.receiveCofirm(
                            pay_type,
                            userIdsStr,
                            moneyStr,
                            markStr,
                            dtStr,
                            EncryptUtils.encodeMD5String(
                                "type=$pay_type&userids=${EncryptUtils.encodeMD5String(
                                    userIdsStr
                                )}&money=${EncryptUtils.encodeMD5String(moneyStr)}&mark=${EncryptUtils.encodeMD5String(
                                    markStr
                                )}&dt=${dtStr}2bHg2U@nAG7q\$4Fh"
                            )!!
                        ).execute()
                    }
                }
                val body = deferred.await()?.body()
                if(BuildConfig.DEBUG) delay(2000)
                showSuccess.call()
                confirmEnable.value = true
                if (body?.code == 0) {
                    toast("确认收款成功")
                    finish.call()
                    return@launch
                }
            }
        }
    }

    fun getInfo(orderId:Int){
        GlobalScope.launch(Dispatchers.Main) {
            showLoading.call()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.getOrderDesc(orderId.toString()).execute() }
            }
            val body = result.await()?.body()
            showSuccess.call()
            if (body?.code == 0){
                desc = body.data
                money.set(desc?.investor_price)
                orderCode.set(desc?.order_no)
                receiveTime.set(desc?.create_time?.format("yyyy-MM-dd HH:mm"))
//                receiveTime.set((desc!!.pay_time).format("yyyy-MM-dd HH:mm"))
//                completeTime.set(desc.last_notify_time.format("yyyy-MM-dd HH:mm"))
//                log("pay_method_name:${body.data.pay_method_name}")
                collectionType.set(body.data.pay_method_name)
//                log("pay_method_name:${collectionType.get()}")
                commissionMoney.set(desc?.income_profit)
                collectionAcc.set(desc?.account)
                remark.set(desc?.app_remark)
                receiveReady.set(desc?.status == 0)
                val statusStr = when (desc?.sub_status) {
                    0 -> "未支付"
                    1 -> "交易完成 "
                    2 -> "异常完成"
                    3 -> "补单完成"
                    4 -> "异常关闭"
                    5 -> "交易超时"
                    else -> null
                }
                tradingStatus.set(statusStr)
                wxShowName.set(desc?.nickname?.isNotEmpty())
                check_code.set(desc?.check_code)
                wxName.set(desc?.nickname)
                if (desc!!.status == 0) {
                    val time = desc!!.expire_time - System.currentTimeMillis() / 1000
                    job = GlobalScope.launch(Dispatchers.Main) {
                        if (time > 0) {
                            for (i in time downTo 0) {
                                overdueTime.set(i.format("mm分ss秒"))
                                delay(1000)
                            }
                            getInfo(orderId)
                        }
                    }
                }
            }
        }
    }

}